package 算法.练习;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author:谢君臣
 * @Date:2021/6/27-16:55
 * @version:1.0
 * @function:
 */
public class TestThread {
    public static void main(String[] args) {
        AtomicInteger ticket = new AtomicInteger(10000);
        Window1 window = new Window1(ticket);
        Thread thread = new Thread();
        thread.setDaemon(true);
        thread.start();
        for (int i = 0; i < 10; i++) {
            new Thread(window).start();
        }
        while (Thread.activeCount()>2)
            Thread.yield();
        System.out.println(Thread.currentThread().getName() + " -- 票已售完");
    }


}
class Window implements Runnable{
    private volatile Integer ticket;
    private Unsafe unsafe;
    @Override
    public void run() {
        unsafe = reflectGetUnsafe();
        while (ticket>0){
            if(unsafe.compareAndSwapInt(this.ticket,ticket,ticket,ticket-1))
                System.out.println(Thread.currentThread().getName()+"卖出一张票,剩余票数"+ getTicket());
            else
                System.out.println(Thread.currentThread().getName()+"并发修改失败，剩余票数"+ getTicket());
        }
    }
    public Window(Integer ticket) {
        this.ticket = ticket;
    }

    public void setTicket(Integer ticket) {
        this.ticket = ticket;
    }

    public Integer getTicket() {
        return ticket;
    }

    public static Unsafe reflectGetUnsafe() {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return (Unsafe) field.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
class Window1 implements Runnable{

    private AtomicInteger ticket;

    public Window1(AtomicInteger ticket) {
        this.ticket = ticket;
    }

    public Integer getTicket() {
        return ticket.get();
    }

    @Override
    public void run() {
        while (ticket.get()>0){
            if (ticket.decrementAndGet()>=0){
                System.out.println(Thread.currentThread().getName()+"卖出一张票,剩余票数"+ getTicket());
            }
        }
    }
}
